Team LiB
Previous Section Next Section

Variables

Variables are a very important part of any programming language. Without being able to declare variables, the programmer's ability to create useful programs would be severely hindered. A variable is a place to store program-generated data that may or may not change as the program runs. A variable can hold anything from the number of visits to a Web page to a list of items in a customer's shopping cart. A variable consists of two parts, an identifier and a value.

Every variable has an identifier, or name, so that it may be referred to later in the program. The name of the variable can be any legal identifier and is usually chosen so that it will accurately describe the variable's purpose. For example, if a variable is intended to hold the user name of a Web page visitor, an appropriate name for that variable would be userName. Variable names that are not easily understood will seriously impede the readability of a source program.

The second, and most important, part of a variable is its value, or the data that it holds. This can be any of the primitive or abstract data types mentioned above. All variables have the value undefined after they are declared and before they are initialized.

Variable Typing

As I mentioned previously, JavaScript is a loosely typed scripting language. This means that all variables will have the same generic type ‘var’ assigned to them when they are declared. The type of the variable will change behind the scenes as you use it, which could be confusing later on, as you may lose track of what the current variable type is. Luckily, JavaScript has a built-in operator to handle this situation: typeof. The typeof operator returns the type of an unevaluated variable. The typeof operator can return the values ‘number’, ‘string’, ‘variable’, ‘object’, or ‘keyword’. Some examples of typeof use are listed in Table 1.4.

Table 1.4: typeof() return values

Call to typeof

Return Value of typeof Operator


typeof( 123 );

number

typeof( ‘a string’ );

string

typeof( new Date() );

object

typeof( true );

boolean

typeof( null );

object

typeof( parseInt );

function

The typeof operator is very useful in preventing errors before performing arithmetic operations on variables about whose type you are unsure.

Great, so you know the type of your variable. It just so happens that it is the wrong variable type for the job. What can you do? Once again, the designers of JavaScript have provided for that eventuality. There are two built-in functions for converting strings to numbers: parseInt() and parseFloat().

The top-level function parseInt ( string, radix ) takes a mandatory string as a parameter, from which the first integer will be extracted and returned. If the function fails to find a number at the beginning of the string, the value NaN will be returned.The optional parameter radix allows you to specify the number base. The default is 10 for decimal numbers. You might also use a radix of 16 for hexadecimal numbers or a radix of 2 for binary numbers. Any number from 2 to 36 can be used here.

The top-level function parseFloat ( string ) takes a string as a parameter, from which the first floating-point number will be extracted. If the function fails to find a number at the beginning of the string, the value NaN will be returned.

The isNaN ( var ) function was designed to determine if the value returned from either parseInt() or parseFloat() is in fact a number. Calling isNaN () with the return value of either of these functions will determine whether they are numbers. Remember, isNaN returns true if the value passed to it was not a number.

Variable Declaration

Most JavaScript statements you write will have the browser do something with data. The data may come from the site visitor as he enters information into a form element, it may be saved and loaded by the browser from a special file called a cookie, or it may be generated from within the program itself. Regardless of how the data is received, it will most likely be stored within a named memory location, which, as you know, is called a variable. This process can only happen if you reserved the space to store the data.

There are four parts to declaring a variable.

  1. First is the key word ‘var’.

  2. var’ is followed immediately by the name you would like to use for the variable. The name must be a legal identifier.

  3. The variable name is followed by an equals sign (=).

  4. The equals sign is followed by a literal you would like your variable to contain the value of.

Here is the variable declaration syntax:

var <identifier> = <literal>

This will make <identifier> the name of the variable and <literal> the initial value of the variable. The equals sign and literal are optional, but I highly recommend initializing your variables so that they don't contain the value undefined when your program starts.

Variable Scope

The scope of a variable determines where in the program it can be used. JavaScript uses static scoping, which means that if you declare your variables outside of a function, they can be used throughout the program. Variables declared within a function, however, can only be used within the function body.

Following is an example that demonstrates JavaScript's static variable scoping:

<html>
  <head>
    <title>
      JavaScript Professional Projects - Variable Scope
    </title>

    <script language="JavaScript">
    <!--
     var number = 10;

       function func1()
       {
         return( number );
       }

       function func2()
       {
         var number = 35;
         return( number );
       }

       function func3()
       {
         var number = 35;
         return( func1() );
       }
     // -->
     </script>

   </head>

   <body>

     <center>
       <font size=6>JavaScript Professional Projects</font><br>
       <font size=4>Chapter 1: Variable Scope</font>
     </center>

     <br><br>

     <p>
     The value returned from func1 is <b>
     <script language="JavaScript">
     <!--
       document.write( func1() );
     -->
     </script>
     </b>- func1 used the global variable 'number'.<br><br>
     The value returned from func2 is <b>
     <script language="JavaScript"
     <!--
       document.write( func2() ); -->
     </script>
     </b>- func2 used the local variable 'number'.<br><br>
     The value returned from func3 is <b>
     <script language="JavaScript"
     <!--
       document.write( func3() );
     -->
     </script>
     </b>- func3 declared a local variable 'number', but
     then used the returned value from func1 - the global 'number'.
  

</body>

</html>

This example demonstrates one peculiarity that may arise from having local and global variables of the same name. In the example, a global variable ‘number’ is declared and the value 10 is assigned to it. That variable is returned by the function func1 and displayed on the page. In func2, however, a local variable, also named ‘number’, is declared and has the value 35 assigned to it. When the return statement in the function func2 returns ‘number’, it is no longer the global value. The local variable temporarily overrides the global variable. As soon as the end of the second function is reached, all other references to ‘number’ will have the global value of 10 just like before. That means that the variable ‘number’ in the second function only has a local scope and temporarily replaces the global variable of the same name.

When the function func3 is called, it creates a local variable named ‘number’, but then calls the function func1. Because func1 uses the global variable, it returns that value to func3, which is then returned and displayed on the page. This demonstrates that local variables can only be used within the local context in which they were created.

Garbage Collection

In any programming language that allows you to dynamically create new objects (such as with the new operator in JavaScript), there must be some way for you to free up memory that is no longer needed by objects. If you didn't have this ability, your program would continue to use more and more memory until there was none left and the program crashed. This is called a memory leak. In C and C++, garbage collection, the process of freeing up memory, is manual. The programmer has to manually use the delete operator on each object created. In Java, reclaiming memory is automated. The Java Virtual Machine can detect when an object is no longer needed and automatically reclaim the memory used by that object.

Thankfully, JavaScript takes after Java and has automatic garbage collection. In Internet Explorer 3.0 and later, and in Navigator 4.0 and later, garbage collection is implemented without flaw and you need not understand the details. Unfortunately, in earlier versions of Navigator, garbage collection has some problems and you must take certain steps to avoid any errors or crashes. Garbage collection will be covered in depth in Chapter 5, "Object-Oriented JavaScript."


Team LiB
Previous Section Next Section