Greg's Blog

helping me remember what I figure out

Javascript: Best Practice Using the With Statement

| Comments

This section forms part of the discussion surrounding variable scope and scope chain (which is a list of objects searched in order). The with statement allows you to brake that order and insert the object that you created with the with statement and insert it ahead of the scope chain.

Commonly it used to reduce the amount of typing required, i.e. when defining form property names. For example:

with(document.form_name){
 name.value=”“;
}

What happens here is that now the object document.form_name is no longer needed in front of every form property. However there are a few drawbacks to using this technique.

  • For one according to the O’Reilly Javascript book, code optimisation becomes difficult and hence can be slow to process.
  • Secondly functions and variables defined within the statement may display erratic behaviour (what this behaviour is, I can’t tell you just yet as it was beyond the scope of the book).

    Hence it is advisable to simply define a variable that will hole aforementioned object:

    var fn = document.your_form_name;
    fn.name.value=”“;