ECMAScript with Statement

Labeled Statements

The with statement is used to set the scope of code within a specific object.

Its syntax:

with (expression) statement

For example:

var sMessage = "hello";
with(sMessage) {
  alert(toUpperCase());	//Output "HELLO"
}

In this example, the with statement is used with a string, so when calling the toUpperCase() method, the interpreter will check if the method is a local function. If not, it will check the pseudo-object sMessage to see if it is a method of that object. Then, alert outputs "HELLO" because the interpreter found the toUpperCase() method of the string "hello".

Tip:The with statement is a slow-running code block, especially when property values have been set. In most cases, it is best to avoid using it if possible.