Home arrow JavaScript arrow Variables, Functions, and Flow Control
JAVASCRIPT

Variables, Functions, and Flow Control


This two-part series offers a mix of JavaScript tricks to help you with your everyday projects. It is excerpted from chapter 4 of the JavaScript & DHTML Cookbook, Second Edition, written by Danny Goodman (O'Reilly, 2008; ISBN: 0596514085). Copyright 2008 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 5 stars5 stars5 stars5 stars5 stars / 15
December 11, 2009
TABLE OF CONTENTS:
  1. · Variables, Functions, and Flow Control
  2. · 4.2 Creating a Named Function
  3. · 4.3 Nesting Named Functions
  4. · 4.4 Creating an Anonymous Function

print this article
SEARCH DEVARTICLES

Variables, Functions, and Flow Control
(Page 1 of 4 )

4.0   Introduction

This chapter covers a miscellany of core JavaScript topics. A couple of these recipes (or your own variations on them) may be part of your daily menu. If you don't use these constructions frequently, let this chapter serve to refresh your memory, and give you models to get you back on track when you need them.  

Even simple subjects, such as JavaScript variables and functions, have numerous nuances that are easy to forget over time. On another front, scripters without formal programming training tend to be rather loose in their attention to detail in the error department--something that can come back to bite you. On the other hand, the browser implementations of some of the details of exception handling are far from compatible. If you aren't yet using exception-handling techniques in your scripts, you should get to know the concepts. As time goes on and the full W3C DOM becomes implemented in browsers, the notion of "safe scripting" will include regular application of exception-handling practices.

This chapter ends with some suggestions about improving script performance. Most scripts can scrape by with inefficiencies, but larger projects that deal with complex document trees and substantial amounts of hidden data delivered to the client must pay particular attention to performance. You'll learn some practices here that you should apply even to short scripts.

4.1   Creating a JavaScript Variable

Problem

You want to create a JavaScript variable value either in the global space or privately within a function.

Solution

Use the var keyword to define the first instance of every variable, whether you assign a value to the variable immediately or delay the assignment until later. Any variable defined outside of a function is part of the global variable scope:

  var myVar = someValue;

All script statements on the page, including those inside functions, have read/write access to a global variable.

When you define a variable with var inside a function, only statements inside the function can access that variable:

  function myFunction() {
     
var myFuncVar = someValue;
     
...
 
}

Statements outside of the function cannot reach the value of a variable whose scope is limited to its containing function.

Discussion

A JavaScript variable has no inherent limit to the amount of data it can hold. Maximum capacity is determined strictly by memory available to the browser application--information not accessible to your scripts.

Variable scope is an important concept to understand in JavaScript. Not only is a global variable accessible by all script statements in the current window or frame, but statements in other frames or windows (served from the same domain and server) can access those global variables by way of the window or frame reference. For example, a statement in a menu frame can reference a global variable named myVar in a frame named content as follows:

  parent.content.myVar

You don't have to worry about the same global variable names colliding when they exist in other windows or frames, because the references to those variables will always be different.

Where you must exercise care is in defining a new variable inside a function with the var keyword. If you fail to use the keyword inside the function, the variable is treated as a global variable. If you have defined a global variable with the same name, the function's assignment statement overwrites the value originally assigned to the global variable. The safest way to avoid these kinds of problems is to always use the var keyword with the first instance of any variable, regardless of where it's located in your scripts. Even though the keyword is optional for global variable declarations, it is good coding style to use var for globals as well. That way you can readily see where a variable is first used in a script.

Although some programming languages distinguish between the tasks of declaring a variable (essentially reserving memory space for its value) and initializing a variable (stuffing a value into it), JavaScript's dynamic memory allocation for variable values unburdens the scripter of memory concerns. A variable is truly variable in JavaScript in that not only can the value stored in the variable change with later reassignments of values, but even the data type of the variable's value can change (not that this is necessarily good programming practice, but that's simply a by-product of JavaScript's loose data typing).

Speaking of good programming practice, it is generally advisable to define global variables near the top of the script, just as it's also advisable to define heavily used variables inside a function at the top of the function. Even if you don't have a value ready to assign to the variable, you can simply declare the variable as undefined with a statement like the following:

  var myVar;

If you have multiple variables that you'd like to declare, you may do so compactly by separating the variable names with commas:

  var myVar, counter, fred, i, j;

You may even combine declarations and initializations in a comma-delimited statement:

  var myVar, counter = 0, fred, i, j;

In examples throughout this book, you typically find variables being declared or initialized at the top of their scope regions, but not always. It's not unusual to find variables that are about to be used inside a for loop defined (with their var keywords) just before the loop statements. For example, if a nested pair of loops is in the offing, I may define the loop counter variables prior to the outer loop's start:

  var i, j;
  for (i = 0; i < array1.length; i++) {
      for (j = 0; j < array1[i].array2.length; j++) {
          ...
      }
  }

This is merely my style preference. But in any case, this situation definitely calls for declaring the variables outside of the loops for another reason. If you were to use the var keywords in the loop counter initialization statements (e.g., var j=0;), the nested loop would repeatedly invoke the var declaration keyword each time the outer loop executes. Internally, the JavaScript interpreter creates a new variable space for each var keyword. Fortunately, the interpreter is also able to keep track of which variable repeatedly declared is the current one, but it places an unnecessary burden on resources. Declare once, then initialize and reassign values as often as needed. Thus, in complex functions that have two or more outer for loops, you should declare the counter variable at the top of the function, and simply initialize the value at the start of each loop.

As for selecting the names for your variables, there are some explicit rules and implicit customs to follow. The explicit rules are more important. A variable name cannot:

  1. Begin with a numeral
  2. Contain any spaces or other whitespace characters
  3. Contain punctuation or symbols except the underscore character
  4. Be surrounded by quote marks
  5. Be a reserved ECMAScript keyword (see Appendix C)

Conventions among programmers with respect to devising names for variables are not rigid, nor do they affect the operation of your scripts. They do, however, help in readability and maintenance when it comes time to remember what your script does six months from now.

The main idea behind a variable name is to help you identify what kind of value the variable contains (in fact, names are commonly called identifiers). Littering your scripts with a bunch of one- or two-letter variables won't help you track values or logic when reading the script. On the other hand, there are performance reasons (see Recipe 4.8) to keep names from getting outrageously long. The shorter the better, but not to the point of cryptic ciphers. If you need two or more words to describe the value, join the words together via underscore characters, or capitalize the first
character of any words after the first word (a convention used throughout this book). Thus, either of the variable names in the following initializations is fine:

  var teamMember = "George";
  var team_member = "George";

Apply these rules and concepts to the identifiers you assign to HTML element name and id attributes, as well. Your scripts will then have no trouble using these identifiers in DOM object references.

Variable names are case-sensitive. Therefore, it is permissible (although not necessarily advisable) to reuse an identifier with different case letters to carry different values. One convention that you might employ is to determine which variables won't be changing their values during the execution of your scripts (i.e., you will treat them as constants) and make their names all uppercase. Mozilla-based browsers implement a forthcoming ECMAScript keyword called const, which you use in place of var to define a true constant value. No other browser supports this keyword yet, so you can use variables as constants and keep modification statements away from them.

JavaScript assigns data to a variable both "by reference" and "by value," depending on the type of data. If the data is a true object of any kind (e.g., DOM object, array, custom object), the variable contains a "live" reference to the object. You may then use that variable as a substitute reference to the object:

  var elem = document.getElementById("myTable");
  var padWidth = elem.cellPadding;

But if the data is a simple value (string, number, Boolean, object property other than an object), the variable holds only a copy of the value, with no connection to the object from which the value came. Therefore, the padWidth variable shown above simply holds a string value; if you were to assign a new value to the variable, it would have no impact on the table element. To set the object's property, go back to the object reference and assign a value to the property:

  elem.cellPadding = "10";

If an object's property value is itself another object, the variable receives that data as an object reference, still connected to its object:

  var elem = document.getElementById("myTable");
  var elemStyle = elem.style;
  elemStyle.fontSize = "18px";

Exercise care with DOM objects assigned to variables. It may seem as though the variable is a mere copy of the object reference, but changes you make to the variable value affect the document node tree.

Global variables share the same scope with all non-nested named functions. In IE and Safari, this same scope is shared with IDs of HTML element objects. In large projects, you may wish to move the declaration of related groups of variables into a custom object as properties. See Recipe 3.14 for more on this subject.

See Also

Chapters 1, 2, and 3 for a discussion on assigning values of different types--strings, numbers, arrays, and objects--to variables; Recipe 4.8 for the impact of variable name length on performance; Recipe 3.14 for ways to minimize global variable space naming collisions.


blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials