You are here: Reference > JavaScript > core > statements

JavaScript Statements

Statements are the smallest standalone elements of the JavaScript language.

Statements:

Method Support Description
break
The break statement can be used to terminate a loop (while, for, for...in, or do...while), or break out of a switch statement.
const
Declares a read-only variable.
continue
Stops the current iteration and continues the loop with the next step.
debugger
Opens the browser specific script debugger application.
do...while
Executes a specified code repeatedly until the condition expression in the while clause (while(condition)) evaluates to false.
export
Provides access to the properties, functions and objects of a signed script for another signed or unsigned script.
for
Creates a loop that is executed repeatedly while the specified condition is true.
for...in
Iterates a specified variable over all properties of an Object, or all elements in an Array, in arbitrary order, and executes the statement for each property or element.
for each...in
Iterates a specified variable over all properties of an Object. Same as for...in, but it can only be used for objects.
function
Declares a new function with the given parameters.
if...else
Executes different code depending on whether the condition in the if clause is true or false.
import
Enables a script to use the properties, functions and objects of another script that have been exported before.
labeled statement
Provides an identifier for a statement that can be referred to in a break or continue statement.
return
Stops the execution of a function and exits with the specified return value.
switch...case
Allows the execution of different code in different cases. The switch statement provides a way to create a complex case-selection without the use of the if...else statement.
this
Returns a reference to the current object.
throw
Throws an exception that can be handled within the catch block of a try...catch statement to identify the type of script error.
try...catch
Allows to handle of script generated errors.
var
Declares a variable.
while
Executes the specified code repeatedly while the condition expression in the while clause (while(condition)) evaluates to true.
with
Specifies the object for a set of statements.

break

The break statement can be used to terminate a loop (while, for, for...in, or do...while), or break out of a switch statement. The break statement exits from the current loop or switch statement, and causes program control to continue execution immediately after statement.
Syntax:
break [label];
label Optional. Specifies the name of an existing label statement. A label statement is an identifier followed by a colon that applies to the next statement in the source. A break statement can reference such a label statement only if it is within the statement that contains the break statement. In that case, the break statement causes that the execution of the program to continue immediately after the statement belonging to the referenced label statement.

Example 1

for (var i=0; i < 4; i++) {
    switch (i) {
    case 0:
        alert ("zero");
        break;
    case 1:
    case 2:
        alert ("one or two");
        break;
    default:
        alert ("some other value");
    }
}
Did you find this example helpful? yes no
The output:
Alerts 'zero', 'one or two', 'one or two', 'some other value'.

Example 2

var arr = ["A", "B", "C", "D"];
var str = "";
for (var i=0; i < arr.length; i++) {
    if (arr[i] == "C") {
        break;
    }
    str += arr[i];
}
document.write ("The interlaced array value, until the element is 'C': " + str);
Did you find this example helpful? yes no
The output:
Alerts 'AB'. The str variable contains only the first two elements of the arr array, because the break statement exits the for loop when it reaches the array element "C".

Example 3

var str = "";
MainLoop:
for (var i = 0; i < 3; i++) {
    for (var j = i; j < 3; j++) {
        if (i + j == 3) {
            break MainLoop;
        }
        str += "(" + i + ", " + j + ") ";
    }
}
document.write (str);
Did you find this example helpful? yes no
The output:
Writes '(0, 0), (0, 1), (0, 2), (1, 1)', because the break MainLoop statement jumps over the first for loop, when i is one and j is two.

const

Declares a read-only variable.
A read-only variable cannot be redeclared and its value cannot be modified.
Although this statement is supported by Opera, the read-only feature is not implemented, so it works the same as the var statement.
Syntax:
const variable1 [=value1], variable2 [=value2], ..., variableN [=valueN];
variable Required. Specifies the name of the variable.
value Optional. Specifies the value of the variable.

Example 1

const x = 10;   // causes syntax error in Internet Explorer

                // writes 10
document.write ("The original value of the constant: " + x);

    // the value of x is not modified in Firefox, Google Chrome and Safari
x = 20;

                // writes 10, in Firefox, Google Chrome and Safari, writes 20 in Opera
document.write ("<br />");
document.write ("The value after the modification: " + x);
Did you find this example helpful? yes no

continue

Stops the current iteration and continues the loop with the next step.
The continue statement is similar to the break statement, in the sense that it also terminates the execution of the loop, but not entirely.
  • If it is used within a while or do...while loop, it tests the condition, and if it is true, it executes the loop again.
  • If it is used within a for or for..in loop, it jumps to the next iteration step and if it is allowed, it executes the loop again.
Syntax:
continue [label];
label Optional. Specifies the name of an existing label statement. A label statement is an identifier followed by a colon that applies to the next statement in the source. A continue statement can reference such a label statement only if it is within the statement that contains the continue statement. In that case, the continue statement causes the execution of the program to continue with the next iteration of the statement belonging to the referenced label statement.

Example 1

var arr = ["A", "B", "C", "D"];
var str = "";
for (var i=0; i < arr.length; i++) {
    if (arr[i] == "C") {
        continue;
    }
    str += arr[i];
}
document.write (str);
Did you find this example helpful? yes no
The output:
Writes 'ABD', because the continue statement causes the program to continue with the next iteration of the for statement.

Example 2

var arr = ["A", "B", "C", "D"];
var str = "";
var i = 0;
while (i < arr.length) {
    if (arr[i] == "C") {
        i++;
        continue;
    }
    str += arr[i];
    i++;
}
document.write (str);
Did you find this example helpful? yes no
The output:
Writes 'ABD', because the continue statement causes the program to continue at the beginning of the while statement.

Example 3

var str = "";
MainLoop:
for (var i = 0; i < 3; i++) {
    for (var j = i; j < 3; j++) {
        if (i + j == 3) {
            continue MainLoop;
        }
        str += "(" + i + ", " + j + ") ";
    }
}
document.write (str);
Did you find this example helpful? yes no
The output:
Writes '(0, 0), (0, 1), (0, 2), (1, 1), (2,2)', because the continue MainLoop statement jumps to the beginning of the first for loop, when i is one and j is two.

debugger

Opens the browser specific script debugger application.
Syntax:
debugger;

Example 1

var str = "test";
debugger;   // Opens the browser specific script debugger application
Did you find this example helpful? yes no
You can watch the str variable in the debugger.

do...while

Executes the statements within the loop first. While the given condition (while(condition)) evaluates to true, the statements within the loop are executed repeatedly.
Syntax:
do {
    [statements]
} while (condition);
statements Optional. Statements that need to be executed repeatedly.
condition Required. When the condition evaluates to true, the loop is executed again, else the do...while loop is terminated.

Example 1

var arr = ["A", "B", "C", "D"];
var idx = 0;
var str = "";
do {
    str += arr[idx];
    idx++;
}
while (idx < 2);
document.write (str);
Did you find this example helpful? yes no
The output:
The str variable contains 'AB', because the while statement returns true only until the idx variable is lower than 2.

export

Provides access to the properties, functions and objects of a signed script for another signed or unsigned script.
The property, object or function must be exported first by the signed script, and then it must imported by the import statement in the script where the member is to be used. The Firefox export/import feature only works for signed scripts. To get more information about signed scripts, please visit the Signed Scripts in Mozilla page.
Syntax:
export name1, name2, ..., nameN;
export *;
name Optional. The name of the property, object or function to export.
* Optional. Exports all properties, functions and objects from the script.

for

Creates a loop that is executed repeatedly while the specified condition is true.
Syntax:
for ([init]; condition; [next]) {
    [statements]
}
init Optional. An expression that initializes variables. The initialization is executed only once, before the loop is started.
condition Required. Executed every time before the loop iteration. If the condition evaluates to true, the loop is executed again, else the loop is terminated.
next Optional. An expression that is evaluated at the end of each loop iteration.
statements Optional. Statements that need to be executed repeatedly.

Example 1

for (var i=0; i < 10; i++) {
        // This statement will be executed 10 times
    document.write (i + "<br />");
}
Did you find this example helpful? yes no
The i variable is declared with an initial value of 0.
After that, the for statement checks whether the value of i is lower than 10. If it is lower, it executes the document.write method. At the end of the loop, the value of i is incremented by one (i++) and the first iteration is finished. Before the next iteration, it checks the value of i. If it is lower than 10, the loop is continued, else it is terminated.

Example 2

var arr = [10, -2, 20];
for (var i = 0; i < arr.length; i++) {
    document.write (i + ": " + arr[i] + "<br />");
}
Did you find this example helpful? yes no
This example iterates over the indeces of an array, in ascendent order.

Example 3

var arr = [10, -2, 20];
for (var i = arr.length - 1; i >= 0; i--) {
    document.write (i + ": " + arr[i] + "<br />");
}
Did you find this example helpful? yes no
This example iterates over the indeces of an array, in descendant order.

for...in

Iterates a variable over the names of an object's members and executes the specified statements in each loop.
Syntax:
for (variable in object) {
    [statements]
}
variable Required. A variable that iterates over the names of an Object's members.
object Required. Names of the specified Object's members will be iterated.
statements Optional. The statements that are executed in each loop.

Example 1

var obj = {first: 1, second: 2, third: 3};
for (var i in obj) {
    document.write (i + ": " + obj[i] + "<br />");
}
Did you find this example helpful? yes no
The i variable iterates over the names of the obj's members and the write method prints the name and the value of the members into the document.

Example 2

for (var i in window.navigator) {
    document.write (i + "<br />");
}
Did you find this example helpful? yes no
The i variable iterates over the names of the window.navigator object's members, and the write method prints the name of members into the document.

Example 3

Array.prototype.AddCherry = function () {
    return this.push ("cherry");    // call Array.push method
}


var arr = [10, -2, 20];
for (var i in arr) {
    document.write (i + ": " + arr[i] + "<br />");
}
Did you find this example helpful? yes no
Do not use the for...in statement to iterate over the indices of an array!
Indices of an array behave like member names, so the for...in statement iterates over them, but if the array has other members, the for...in statement also finds of them.
If you want to iterate over the indices of an array, use the for statement and the length property of the array.

for each...in

Iterates a variable over the values of an Object's members and executes the specified statements in each loop. The for...in statement is similar to the for each...in statement, but it iterates over the names not the values of members.
Syntax:
for each (variable in object) {
    [statements]
}
variable Required. A variable that iterates over the values of an Object's members.
object Required. Values of the specified Object's members will be iterated.
statements Optional. The statements that are executed in each loop.

Example 1

var obj = {first: 1, second: 2, third: 3};
for each (var i in obj) {
    document.write (i + "<br />");
}
Did you find this example helpful? yes no
The i variable iterates over the values of the obj's members and the write method prints the values into the document.

Example 2

Array.prototype.AddCherry = function () {
    return this.push ("cherry");    // call Array.push method
}


var arr = [10, -2, 20];
for each (var i in arr) {
    document.write (i + "<br />");
}
Did you find this example helpful? yes no
Do not use the for each...in statement to iterate over the elements of an array!
Indices of an array behave like member names, so the for each...in statement iterates over their values, but if the array has other members, the for each...in statement also finds of them.
If you want to iterate over an array, use the for statement and the length property of the array.

function

Declares a new function with parameters.
When calling a function with fewer parameters than declared, the rest of the parameters will be undefined inside the function. If you need a variable-length parameter list, use the arguments object inside the function to get all parameters by the specified caller. See Example 2 and the page for the arguments object for details.
Use the return statement within a function to return a value.
Syntax:
function name ([param1] [, param2] [..., paramN]) {
    [statements]
}
name Required. Specifies the name of the function, which can be used as a reference later.
param Optional. A comma-separated list of arguments passed to the function.
statements Optional. The statement that is executed when the function is called.

Example 1

function GetSum (arg1, arg2) {
    var sum = arg1 + arg2;
    return sum;
}

var result = GetSum (3, 21);
document.write (result);
Did you find this example helpful? yes no
The GetSum function returns the sum of the given two numbers.

Example 2

function GetSum () {
    var sum = 0;
    for (var i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }
    return sum;
}

var result = GetSum (3, 2, 2, 3);
document.write (result);
Did you find this example helpful? yes no
The GetSum function returns the sum of the given numbers.

if...else

Executes different statements depending on the value of a condition.
Syntax:
if (condition) {
    [statements1]
}
[else {
    [statements2]
}]
condition Required. An expression that evaluates to true or false.
statements1 Optional. Statements that are executed if the condition is true.
statement2 Optional. Statements that are executed if the condition is false.

Example 1

if (x == 1) {
    y = 2;
}
Did you find this example helpful? yes no
If the 'x' variable is equal to 1, y set to 2.

Example 2

if (x == 1) {
    if (y == 2) {
        z = 3;
    } else {
        z = 4;
    }
}
Did you find this example helpful? yes no
If the 'x' variable is equal to 1 and the 'y' variable is equal to 2, then 'z' is set to 3, but if the 'x' variable is 1 and 'y' is not equal to 2, then 'z' is set to 4.

import

Enables a script to use properties, functions and objects of a signed script that have been exported before.
The property, object or function must be exported first by the signed script, and then it must imported by the import statement in the script where the member is to be used. The Firefox export/import feature only works for signed scripts. To get more information about signed scripts, please visit the Signed Scripts in Mozilla page.
Syntax:
import object.name1, object.name2, ..., object.nameN;
import object.*;
object.name Optional. The object and name of the property, object or function to import.
object.* Optional. Imports all properties, functions and objects of the given object.

label

Provides an identifier for a statement that can be used to be referred to by a break or continue statement.
Labels are commonly used to identify the point where the execution of the code will be continued.
Syntax:
label:
    statement
label Required. An identifier that can be used as a label.
statement Required. The statement associated with the label.

Example 1

var str = "";
MainLoop:
for (var i = 0; i < 3; i++) {
    for (var j = i; j < 3; j++) {
        if (i + j == 3) {
            break MainLoop;
        }
        str += "(" + i + ", " + j + ") ";
    }
}
document.write (str);
Did you find this example helpful? yes no
The output:
Writes '(0, 0), (0, 1), (0, 2), (1, 1)', because the break MainLoop statement jumps over the first for loop, when i is one and j is two.

return

Stops the execution, and exits from a function with the specified return value.
Syntax:
return [value];
value Optional. The value that is returned by the function.

Example 1

function GetSum (arg1, arg2) {
    var sum = arg1 + arg2;
    return sum;
}

var result = GetSum (3, 21);
document.write (result);
Did you find this example helpful? yes no
The GetSum function returns the sum of the given two numbers (in this example: 24).

switch...case

Allows the execution of different code in different cases. The switch statement provides a way to create a complex case-selection.
Program control searches for a match between the labeled cases for the value and the type of the expression specified in the switch statement. If a match is found, execution continues after the first matching case clause. If no match is found, execution continues after the default clause or after the end of the switch statement if a default clause is not defined.
Syntax:
switch (expression) {
    case label1:
        [statements]
        [break;]
    case label2:
        [statements]
        [break;]
    default:
        [statements]
        [break;]
}
expression Required. The expression whose evaluated value is compared to the value of each case label in the structure.
labelN Required. An identifier used to match against expression.
break Optional. Breaks out of a switch statement. A label can be used with the label statement. If no label is specified, execution will continue after the switch statement, else after the statement that belongs to the label. See Example 2 and the break statement for details.
statements Optional. The statements that are executed if the expression matches the associated label.

Example 1

for (var i=0; i < 4; i++) {
    switch (i) {
    case 0:
        alert ("zero");
        break;
    case 1:
    case 2:
        alert ("one or two");
        break;
    default:
        alert ("some other value");
    }
}
Did you find this example helpful? yes no
The output:
Alerts 'zero', 'one or two', 'one or two', 'some other value'.

Example 2

MyLoop:
for (var i=0; i < 4; i++) {
    switch (i) {
    case 0:
        alert ("zero");
        break;
    case 1:
    case 2:
        alert ("one or two");
        break MyLoop;
    default:
        alert ("some other value");
    }
}
Did you find this example helpful? yes no
The output:
Alerts 'zero', 'one or two'.

this

Returns a reference to the current object.
Typically used in methods of objects or in event handlers to refer to the current object.
Note that the this keyword refers to the window object in the following cases:
  • in the outermost context, outside any function block
  • in functions that are not object contructors and not methods of objects
  • in inline event handler functions for the onload, onunload and onbeforeunload events on the body.
See Example 5 for details.
Syntax:
this;

Example 1

<head>
    <script type="text/javascript">
        function ChangeColor (elem) {
            elem.style.color = "#ff0000";
        }
    </script>
</head>
<body>
    <button onclick="ChangeColor (this);">Change my text color to red!</button>
</body>
Did you find this example helpful? yes no
This example shows how to pass the object to an event handler on which the event listener was registered. Note that the object on which the event has occurred and the object referred to by this may be different. See the next example.

Example 2

<head>
    <script type="text/javascript">
        function CheckTarget (event, div) {
            var target = event.target ? event.target : event.srcElement;

            if (target == div) {
                alert ("You have clicked on the blue field.");
            }
            else {
                alert ("You have clicked on the button.");
            }
        }
    </script>
</head>
<body>
    <div onclick="CheckTarget (event, this);" style="width:300px; height:100px; background-color:#8080ff;">
        Click on this text and on the button next.
        <button>A simple button</button>
    </div>
</body>
Did you find this example helpful? yes no
This example checks whether the element on which the event has occurred and the element on which the event was regitered are the same.

Example 3

function Rectangle (a, b){
    this.Init (a, b);
}

    // constructor
Rectangle.prototype.Init = function (a, b) {
    this.a = a;
    this.b = b;
};

Rectangle.prototype.Area = function () {
    return this.a * this.b;
};

var rect = new Rectangle (2, 3);
document.write (rect.Area ());  // display: 6
Did you find this example helpful? yes no
This example illustrates the use of the this statement for objects.

Example 4

<head>
    <script type="text/javascript">
            // ColorChanger object
        function ColorChanger (elem, colorTo) {
            this.Init (elem, colorTo);
        }

        ColorChanger.prototype.Init = function (elem, colorTo) {
            this.elem = elem;
            this.colorTo = colorTo;

                // save a reference to the current object
            var _this = this;
                /* use the saved reference within the registered function 
                 (the 'this' statement within the registered function refers to the function
                 not the current instance of ColorChanger) */
            this.elem.onclick = function () {_this.ChangeColor ()};
        }

        ColorChanger.prototype.ChangeColor = function () {
            this.elem.style.color = this.colorTo;
        }
        

            // Attach ColorChanger instances to the buttons
        function OnDocLoad () {
            var button1 = document.getElementById ("button1");
            var button2 = document.getElementById ("button2");

            var colorChanger1 = new ColorChanger (button1, "#ff0000", 1);
            var colorChanger2 = new ColorChanger (button2, "#0000ff", 2);
        }
    </script>
</head>
<body onload="OnDocLoad ()">
    <button id="button1">Change my text color to red!</button>
    <button id="button2">Change my text color to blue!</button>
</body>
Did you find this example helpful? yes no
This example shows how to register object methods as event handlers.

Example 5

<head>
    <script type="text/javascript">

        var refToWin = "the this keyword refers to the window object";
        var refToNotWin = "the this keyword refers to something else than the window object";


        document.write ("Outermost context: ");
        if (this === window) {
            document.write (refToWin);
        }
        else {
            document.write (refToNotWin);
        }
        document.write ("<br /><br />");


        function CheckThis () {
            if (this === window) {
                document.write (refToWin);
            }
            else {
                document.write (refToNotWin);
            }
        }

        document.write ("In functions: ");
        CheckThis ();
        document.write ("<br /><br />");

        document.write ("In object constructor functions: ");
        var obj = new CheckThis ();
        document.write ("<br /><br />");



        function OnDocLoad (obj) {
            var message = "In a handler for the body.onload event: ";
            message += (obj === window) ? refToWin : refToNotWin;
            alert (message);
        }
    </script>
</head>
<body onload="OnDocLoad (this)">
</body>
Did you find this example helpful? yes no
This example tests the this keyword in some cases.

throw

Allows throwing an exception that can be handled in the catch block of a try...catch statement to identify the type of an error.
Syntax:
throw expression;
expression Required. The exception to throw. Can be a string, integer, boolean or an arbitrary object. JavaScript engines use the Error object for exception handling.

Example 1

<head>
    <script type="text/javascript">
        function CheckValue () {
            var input = document.getElementById ("myInput");
            var num = parseInt (input.value);
            try {
                if (isNaN (num)) {
                    throw "NaN";
                } 
                if (num > 5) {
                    throw "higher";
                } 
                if (num < 0) {
                    throw "smaller";
                }
                alert (num + " was entered.");
            } catch (e) {
                switch (e) {
                case "NaN":
                    alert ("Error! The value is not a number.");
                    break;
                case "higher":
                    alert ("Error! The value is too high.");
                    break;
                case "smaller":
                    alert ("Error! The value is too low.");
                    break;
                };
            }
        }
    </script>
</head>
<body>
    Please type some text in the input field!
    <br />
    Click on the button to verify that the input field contains a number between 0 and 5.
    <br />
    <input id="myInput" value="10" />
    <button onclick="CheckValue ();">Check value</button>
</body>
Did you find this example helpful? yes no
This example throws an exception if the given string is not a number or is not between 0 and 5.

try...catch

Allows to handle script generated errors for the statements inside the try block. When an error occurs inside the try block, it raises an exception. The exception can be catched with the catch statement. An exception can be thrown directly with the throw statement, too.
With the finally statement, you can define statements that are always executed, regardless of whether an exception has occurred or not.
Syntax:
try {
    try_statements
}
[catch (exception){
    [catch_statements]
}]
[finally {
    [finally_statements]
}]
try_statements Required. The statements where the error may occur.
exception Required. A variable that refers to the error. JavaScript engines use the Error object for exception handling. When the exception is created by a throw statement, then the variable refers to the object specified in the throw statement.
catch_statements Optional. The statements to execute when an error occurs within the try block.
finally_statements Optional. The statements that are always executed, regardless of whether an exception has occurred or not.

Example 1

try {
    unknownFunction ();
}
catch(e) {
    document.write ("The error message: <b>" + e.message + "</b>");
    if ('number' in e) {
        document.write ("<br />");
        document.write ("The error code: <b>" + e.number + "</b>");
    }
    if ('lineNumber' in e) {
        document.write ("<br />");
        document.write ("The error occurs at line: <b>" + e.lineNumber + "</b>");
    }
}
Did you find this example helpful? yes no
This example catches an exception and displays information about the error.

Example 2

<head>
    <script type="text/javascript">
        function CheckValue () {
            var input = document.getElementById ("myInput");
            var num = parseInt (input.value);
            try {
                if (isNaN (num)) {
                    throw "NaN";
                } 
                if (num > 5) {
                    throw "higher";
                } 
                if (num < 0) {
                    throw "smaller";
                }
                alert (num + " was entered.");
            } catch (e) {
                switch (e) {
                case "NaN":
                    alert ("Error! The value is not a number.");
                    break;
                case "higher":
                    alert ("Error! The value is too high.");
                    break;
                case "smaller":
                    alert ("Error! The value is too low.");
                    break;
                };
            }
        }
    </script>
</head>
<body>
    Please type some text in the input field!
    <br />
    Click on the button to verify that the input field contains a number between 0 and 5.
    <br />
    <input id="myInput" value="10" />
    <button onclick="CheckValue ();">Check value</button>
</body>
Did you find this example helpful? yes no
This example throws an exception if the given string is not a number or is not between 0 and 5.

var

Declares a variable with local scope.
A variable can be defined with or without the var keyword, but syntactically the var keyword is needed. If the var keyword is not used, the variable is undeclared.
When a variable is defined with the var keyword, it can only be used within the block where it is defined. When a variable is defined without the var keyword, it is created as a global variable and can be reached from anywhere in the document, but it is recommended to declare global variables with the var keyword placed outside any function. See the examples below for details.
Syntax:
var variable1 [=value1], variable2 [=value2], ..., variableN [=valueN];
variable Required. Specifies the name of the variable.
value Optional. Specifies the value of the variable.

Example 1

<head>
    <script type="text/javascript">
        var y = 20;

        function SetXValue () {
            var x = 10;
        }

        // executes the SetXValue function at runtime
        SetXValue ();

        function GetValue () {
            if (typeof (x) == "undefined") {
                alert ("Variable x is undefined.")
            }
            else {
                alert ("The value of x is " + x + ".");
            }

            if (typeof (y) == "undefined") {
                alert ("Variable y is undefined.")
            }
            else {
                alert ("The value of y is " + y + ".");
            }
        }
    </script>
</head>
<body>
    <button onclick="GetValue ();">Get the value of variables x and y</button>
</body>
Did you find this example helpful? yes no
This example declares variable x with local scope and variable y with global scope.

while

Executes the code within the loop repeatedly while the given condition (while(condition)) evaluates to true.
Syntax:
while (condition) {
    [statements]
}
condition Required. When the condition evaluates to true, the loop is executed, else the while loop is terminated.
statements Optional. Statements that need to be executed repeatedly.

Example 1

var x = 5;
while (x < 10) {
    x++;
}
document.write (x);
Did you find this example helpful? yes no

with

Marks an object for a set of statements. When the JavaScript interpreter analyzes the code inside a with block and finds an identifier, it tries to find it among the object's members first. Do not use too many with statements in your code, because it causes slower processing.
Syntax:
with (object) {
    [statements]
}
object Required. Specifies the object to mark.
statements Optional. Statements that can refer to the members of the object without prefix.

Example 1

var d,a;
var s = 10;
with (Math) {
    a = pow (s, 2);
    d = sqrt (2 * a);
}
Did you find this example helpful? yes no
In this example the with statement specifies that the Math object is the default object. The pow and the sqrt methods are called without any object, but the interpreter assumes the Math object for these methods.

Example 2

<head>
    <script type="text/javascript">
        function ChangeStyle (element) {
            with (element.style) {
                backgroundColor = "blue";
                // same as element.style.backgroundColor = "blue"
            }
        }
    </script>
</head>
<body>
    <div onclick="ChangeStyle (this)" style="color:red">
        Clicking on this text will change its background color
    </div>
</body>
Did you find this example helpful? yes no
In this example the with statement specifies that the div.style object is the default object. The backgroundColor property is a member of the div.style object.

Example 3

<head>
    <script type="text/javascript">
        function ChangeStyle (element) {
            var color = "blue";
            with (element.style) {
                backgroundColor = color; 
                // same as element.style.backgroundColor = element.style.color
            }
        }
    </script>
</head>
<body>
    <div onclick="ChangeStyle (this)" style="color:red">
        Clicking on this text will change its background color
    </div>
</body>
Did you find this example helpful? yes no
If you use the with statement, be careful with the specified object members. In this example the backgroundColor will be "red" not "blue"!
User Contributed Comments

Post Content

Post Content