Home / Advanced JavaScript Tutorials / Variable and expression shortcuts

 

 

CodingForums
Having trouble with scripting? Visit our help forum to get the answers you need.

Jump to...
-Free JavaScripts
-JS tutorials
-JS Reference
-DHTML/CSS

-Free applets
-Web Tutorials
-Link to Us!

- CSS Drive
- PHP Resources
- Hotels & Vacations
- Bad credit cards
- JavaScript Menus


Red_CurlyC035.gif (995 bytes) The "with" statement

The "with" statement is created to save you a few key strokes when you're writing out a JavaScript object repeatedly. Take a look at the below example:

<script>
document.write('Hi there, how are you?")
document.write('Fine, thanks. And you?')
document.write('Great!')
</script>

This is a short excerpt from a children's textbook (not that I'm still reading that kind of books), and a perfect illustration of an object being repeatedly written out to accomplish something. I used the document object three times to write out three lines of text. There is actually a way to cut the former "three" to just "one", and that is by using the "with" statement:

<script>
with (document){
write('Hi there, how are you?")
write('Fine, thanks. And you?')
write('Great!')
}
</script>

By using the with statement, everything that falls inside of its brackets ({ }) default to the object specified in it's parameter. That way, you only need to type the object name once.

Ok, you're not exactly convinced of the "usefulness" of the "with" statement at this point. How about I provide a demonstration of it on a more tedious-to-write JavaScript object? Hmm, how about a form object?

Referencing a form element in JavaScript is a real pain in the neck- First, begin with the document object, then the form's name, and then, the name of the form element's name:

<form name="test">
<input type="text" value="Hi there!" name="test2">
</form>

<script>
window.status=document.test.test2.name
var temp=document.test.test2.value
</script>

Let's use the "with" statement to save ourselves some typing:

<script>
with (document.test.test2){
window.status=name
var temp=value
}
</script>

Remember, the "with" statement can be used with any JavaScript object to avoid having to repeatedly write the object out when referencing it multiple times.

-Tutorial introduction
-Declaring many variables at once
-Assignment operator shortcuts
-The "with" statement
-The "?" conditional expression statement

The "?" conditional expression statement


http://javascriptkit.com
Copyright © 1997-2005 JavaScript Kit. NO PART may be reproduced without author's permission.