Understanding JavaScript and Types

an article added by: Sonja Lande at 05312007


In: Categories » Computers and technology » AJAX » Understanding JavaScript and Types

Understanding JavaScript and Types

Problem You want to work around the fact that JavaScript does not have types declared for its variables. Theory JavaScript code does not have any variables with a declared type. The lack of typed variables is apparent when you declare functions. That said, not having typed variable declarations does not mean JavaScript has no types or no type safety. Let’s start out with the simple declaration of a function, as illustrated by the following example.

    Source: /website/ROOT/ajaxrecipes/javascript/expectations.html
    function AddTwoNumbers(num1, num2) {
    return num1 + num2;
 }

The AddTwoNumbers function has two parameters, num1 and num2, and represents two individual numbers. In the implementation of AddTwoNumbers, the two numbers are added together and the value is returned. This way of declaring and using a function is common in other programming languages. The result of adding the numbers num1 and num2 is returned to the caller as follows: assertEquals(4, AddTwoNumbers(2, 2)); The assertEquals function is used to verify that when the AddTwoNumbers function is called with 2 and 2, 4 is generated as a result. When you run the code, everything works as expected, but can you feel assured that everything is correct?

The answer is no, you cannot feel assured, because some misleading assumptions are being made. The AddTwoNumbers function declares two numbers, but the assumption that num1 and num2 are numbers is not reasonable. In JavaScript, variables are not type declared. Once assigned to a type, a variable is type-safe, but you don’t know what the type is until the variable is assigned. Therefore, with respect to the function, the types num1 and num2 are not known. Solution A safer way to implement AddTwoNumbers is as follows.

    Source: /website/ROOT/ajaxrecipes/javascript/expectations.html
    function AddTwoNumbersDisplayTypes( num1, num2)  {
    var val1 = parseInt( num1);
    var val2 = parseInt( num2);
    if( isNaN( val1) || isNaN( val2)) {
    throw new Error( "num1, (and/or) num2 are  neither a number or string");
    }
    info( "AddTwoNumbersDisplayTypes",  typeof( num1));
    info( "AddTwoNumbersDisplayTypes",  typeof( num2));
    return val1 + val2;
 }

In the modified implementation, the parseInt method, which is used to convert a string into a number, is applied to both num1 and num2. The result of parseInt is an integer value that allows num1 and num2 to be added together. The num1 and num2 parameters are verified to be numbers using the isNaN operator. The return value of isNaN is a true or false value. If either of the values returns false, then num1 or num2 is not a number and an exception is thrown. In this modified implementation, it would seem that very little could go wrong. Looking at the implementation of adding two numbers, you may wonder how using a dynamic language like JavaScript is an advantage over using another programming language.

The additional code used to verify whether or not the correct types are used would be tedious if that sort of logic was implemented for all functions. In other programming languages such as Java and C#, adding two numbers together safely is completely trivial. Granted, if you are going to perform a large number of numerical calculations, then JavaScript is probably not the most suitable programming languages. But when you need to write an application to get something done, and you don’t want to mess around with the lower-level details of which type does what, JavaScript is the better choice. The modified source code is an example of writing defensive code, which is a good practice, but don’t take it too far and let it make you paranoid. You want code that does what it is supposed to do, and when it doesn’t, it should generate explicit errors in other words, you want code that screams when an error occurs. The code that captures the scream should then do something with it. When writing functions, the objective is to write an implementation that has defensive code appropriate to the expectations of the function. When writing code in a dynamic language such as JavaScript, expectations and conventions play extremely important roles. When writing code using a programming language such C# or Java, programmers are expected to account for every situation that works and does not work. Let’s therefore rewrite our addition function to implement our expectations and use a convention. The first step is to write the tests and think about what is and isn’t appropriate. The following implementation reflects our expectations.

    Source: /website/ROOT/ajaxrecipes/javascript/expectations.html
    classical_add_display_types : function() {
    assertEquals( 4, AddTwoNumbersDisplayTypes( 2,  2));
    assertEquals( 4, AddTwoNumbersDisplayTypes(  "2", 2));
    try {
    AddTwoNumbersDisplayTypes( new Object(), 2);
    testManager.failed();
    return;
    }
    catch( e) {
    info( "classical_add_display_types",  "Expected error (" + e.toString() + ")");
    }
    testManager.success();
 },

The first two assertEquals method calls reflect the expectation that we could add a number that is either a string or a numeric value. The expectation of adding two numeric values is obvious because typically you add two numbers together. The expectation of being able to recognize two buffers as numbers is appropriate because we are dealing with HTML forms. HTML form elements store their values as buffers. So when performing mathematical operations using data from HTML form elements, we expect the formulas to handle the conversion from buffers to numeric values. After the method calls that implement tests of our expectations, the code within the exception block implements something we would expect not to work.

Calling the addition with an object, where a property of the object might reference a number, is not something we expect the addition function to figure out. Here we expect an error to be generated. The code that is not expected to work, or at least can be expected to fail, is wrapped in an exception block. The role of the expectation is required in both the function and the caller of the function, as illustrated in the example. In JavaScript, functions must meet certain expectations, so you should observe the following points when writing them:

• Variables are not declared using types, and when the variables are not assigned they are considered typeless.

• Once assigned, variables look, feel, and behave like types.

• When implementing functions, you are writing blocks of code that implement expectations.

• To properly meet expectations, you need to write tests.

• When expectations are not met, the errors should be obvious and their accompanying messages should be explanatory.

• If you want to verify what type a variable is, use typeof. Do not use a simple object or check.

• When implementing expectations, don’t be paranoid and attempt to create a type system by verifying the exact details of every variable and every parameter.

legal notice

Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.

Useful tools and features

Link to this article from your page    Send this article to you or to a friend
If you like this article (tutorial), please link to it from your web page using the information above.

related articles

1. Understanding the Definition and Philosophy of REST
Understanding the Definition and Philosophy of REST REST is a controversial topic among Web service enthusiasts, because it’s considered to stand for the opposite of what Web services and SOA are trying to achieve. The problem with this thinking is that REST is not in contradiction with the abstract definition of SOA and Web services. REST is in contradiction with technologies such as SOAP, WSDL, and WS-* specifications. The following offers a quick definition of REST:...

2. The Easiest Way to Get Started with Ajax and REST
The Easiest Way to Get Started with Ajax and REST Problem You want to know the best way to get started with writing Ajax and REST. Solution When developing an Ajax and REST application, you must decide on the tools and frameworks you’ll use. The choice is simple: Use whatever you’re using today, and write some Ajax applications. You don’t need to change the tools you’re using today. Whether you’re using ASP.NET, JavaServer Pages (JSP), PHP, Ruby, or Python, you...

3. Testing a Dynamic Contract with Ajax
Coding the Contract Using Test-Driven Development Techniques Coding the contract using agile and test-driven development techniques requires writing a number of tests and implementing aMock URL layer. Problem You want to code the contract using these development techniques. Solution To demonstrate, let’s define a use case, implement the use case as a contract, write a test case(s) to implement the contract, implement the contract in the Mock URL, and finally...

4. Testing the Client Side Logic
Problem You want to effectively test your application’s client-side logic. Theory Testing GUI code tends not to be a productive task because of the complications that arise. The main complication is how to test the correctness of a user interface. Imagine a situation where clicking a button causes a table to be filled with data. Now imagine that when a check box is checked and the button is clicked again, a different table is filled with content. The fact that clicking the same button results in two ...

5. Coding Using Conventions and Not Configurations
Coding Using Conventions and Not Configurations Problem You want to make your JavaScript constructs more efficient by applying the Rails “convention over configuration” principle to them. Theory You may already be familiar with the programming platform Ruby on Rails, which is used to build Web applications. The focus of this recipe is not Ruby on Rails, but one aspect of Ruby on Rails namely, convention over configuration (see http://en.wikipedia.org/wiki/ Ruby_on_Rails for m...

6. Advantage of parameterless functions in JavaScript
Using Parameterless Functions Problem You want to take advantage of parameterless functions in JavaScript. Theory JavaScript functions for the most part have parameters. You may think that the previous sentence states the obvious after all, without parameters, what data could be passed to a function? JavaScript has the ability to declare functions that have no parameters, even though the caller of the function has passed parameters to the function. For example, let’s look at...

7. JavaScripot Functions
Treating Functions Like Objects Problem You want to take advantage of the fact that functions are objects (remember, everything is an object in JavaScript). Theory Many people think that a function is some keyword used in JavaScript. A function is also an object that can be manipulated. Knowing that a function is an object makes it very interesting from the perspective of writing JavaScript code, because the code can treat the function like another other object. This mean...

8. Implementing an Error and Exception Handling Strategy
Implementing an Error and Exception Handling Strategy Problem You want to implement a clean error and exception handling strategy in your applications, to make them run more smoothly. Theory Of course, you might argue that one error is a dialog box and the other is generated in the JavaScript console. The fact that one browser uses a dialog box to show an error and the other does not is a browser issue, not an error issue. A concise way of classifying the two errors is to ...