3.2. Variable Types in JavaScript

When working with any programming language, you as a developer need to be concerned with the data types that you are working with. C# is a strongly typed language. This means that whenever you are going to work with a specific data point, you first need to cast the object you are working with to a specific data type. For example, to work with a string in C#, you are going to have to use something like the following bit of code:

string myString = "Hello World!";

JavaScript, on the other hand, is often characterized as having no data types. Everything in JavaScript is just an object. This is basically a true statement; however, some primitive types can be assigned to variables, and the variables can pick up those types (this is similar to variants for those of you with COM experience). Numbers, strings, Booleans, and functions are the primitive types in JavaScript. They are the building blocks for all objects in JavaScript. Even the higher order "types" that are predefined, such as arrays and regular expressions, are just collections of the basic types.

Listing 3-7 declares a few variables, assigns them integer values, and then displays true or false after treating them as Boolean values. The key thing to note is that JavaScript follows the C-style convention of treating 0 as false and everything else as true. When the page is run, the result is to display true for one, false for zero, and true for negative one.

Example 3-7. Working with Booleans in JavaScript
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Booleans</title>

    <script type="text/javascript">
        var myOne = 1;
        var myZero = 0;
        var myNegativeOne = −1;

        if(myOne) {
            alert(true);
        }

        if(!myZero) {
            alert(false);
        }

        if(myNegativeOne) {
            alert(true);
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>

To the .NET developer, this set of basic types is pretty straightforward. Strings, numbers, and Booleans are fundamental to all programming tasks, so having them as basic types seems natural. However, you cannot anchor a variable to specific data types when they are declared in JavaScript, so you have to use greater care when writing code. You will not get an error if you assign a string to a number variable, since the variable is not locked down to holding only numbers. Still, this can generate an odd error at runtime when you try to access that variable as a number. This is a common problem of all typeless interpreted languages.

Without the ability to tie variables to specific types, you lack static type safety. The language is not compiled; it is interpreted. Types can be created at runtime and dynamically altered during script execution. In other languages, you must declare a type for a variable, and if the variable refers to an object of a different type, you get a compilation error. Another option in C++ and .NET languages is to coerce variables carefully from one type to another. This is not the case in JavaScript. There is only one type of variable declaration, and no type specifier is permitted. Any variable can refer to any kind of object at any time. In Listing 3-8, a single variable is declared and then assigned to the fundamental types used in the previous example. This example uses the typeof operator to show that the type reference changes while the script is being executed.

Example 3-8. Changing type references at runtime
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Working with types</title>

<script type="text/javascript">
    var variable;
    alert(typeof(variable));//refers to something undefined;

    variable = 1;// refers to a number
    alert(typeof(variable));

    variable = true; //refers to a Boolean
    alert(typeof(variable));

    variable = "This is my string."; //refers to a string

    alert(typeof(variable));
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>

Running this example, you will get four alert boxes (message boxes). The first returns the type of the variable object based upon the declaration of the following:

var variable;

Since nothing is assigned to this object in this statement, there is actually no type associated with it, and you will therefore, get an alert as is shown here in Figure 3-4.

Figure 3-4. Figure 3-4

The next three alerts also display the type that the variable object is set at. The type is actually inferred from the value that is assigned to the object at the time. An assignment of 1 means that the object should be treated as a number and an assignment of a string means that the variable object is automatically treated as a string object. Based upon the assignments, you will see the rest of the alerts as presented here in Figure 3-5.

Figure 3-5. Figure 3-5

To show how this works in greater detail, take a look at the example in Listing 3-9.

Example 3-9. Adding two numbers together
<script type="text/javascript">
    var variable1 = 3;
    var variable2 = 5;
    var result;

    result = variable1 + variable2;

    alert(typeof(result));
    alert(result);
</script>

In this example, three objects are created. The first two, variable1 and variable2 are assigned numbers as values. This also means that these objects are of type number upon assignment. The third object declared is the result object and upon assignment, this object is in an undefined state. Then, the result object is populated with the variable1 and variable2 objects added together with the result = variable1 + variable2; statement.

This produces the alerts illustrated in Figure 3-6.

Figure 3-6. Figure 3-6

Though, consider the following change to the code from Listing 3-9. The change of code is here in Listing 3-10 and changes the 3 and 5 values to strings of "3" and "5".

Example 3-10. Adding two strings together
<script type="text/javascript">
    var variable1 = "3";
    var variable2 = "5";
    var result;

    result = variable1 + variable2;

    alert(typeof(result));
    alert(result);
</script>

This instead results in the alerts presented here in Figure 3-7.

Figure 3-7. Figure 3-7

JavaScript does not consider this to be an error, because this is how it was designed to work (but this particular code snippet may not be a wise way to write your code, of course). Any variable can point to any object at any time. At first glance, this lack of type checking may not seem important, but it is a key element to the power that JavaScript can bring to your code. It is also central to some of the complications you will encounter when programming with JavaScript.

The Microsoft AJAX Library takes advantage of the extensible nature of JavaScript to extend its functionality to provide a more familiar object-oriented approach to development, even when using a typeless language, by layering some additional standard type treatment onto the language.

Microsoft could not modify the underlying typeless nature of the language, but they were able to provide a better way of using it that allows you to represent types in some ways that help to mitigate the underlying limitations.

In addition to the basic building block types, two other types are central to programming in JavaScript. Anything that is not a number, Boolean, or string is either a function or an object. A function in JavaScript is a first-class type. It can be passed as an argument to another object. A function can receive arbitrary arguments to act on for execution. A function can return primitive types, or it can even return a new function. Listing 3-11 presents an example that is admittedly not very useful in the real world but illustrates this point.

The CreateFunction() function actually creates and returns one of two new functions that are stored and then invoked by calling CreateFunction(). By calling CreateFunction() you produce a function to double or triple numbers. In reality, you would just use the built-in math libraries for this sort of thing.

Example 3-11. Working with functions
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Code Test Page</title>
</head>
<body>

    <script type="text/javascript">
        function CreateFunction(s) {
            if (s ===2) {
                return function (s) { return s*2; }
            }
            else if( s=== 3) {
                return function(s) { return s*3; }
            }
        }

        var DoubleIt = CreateFunction(2);
        var TripleIt = CreateFunction(3);

        alert(DoubleIt(2));
        alert(TripleIt(4));

        alert(typeof(CreateFunction));
        alert(typeof(DoubleIt));
    </script>

</body>
</html>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset