Computer Languages

Numerical Input and Output with JavaScript

[ Back to Lecture Notes ] [ JavaScript ]

JavaScript Data Types

JavaScript is what is commonly called an "untyped" language. In actual fact it is more a "loosely typed" or "dynamically typed" language. Many languages require you to declare the data type of your variables. For example:

    /* C/C++ */
    int count = 10;                 /* count is type int (integer) */
    char msg[] = "Enter name: ";    /* msg is a string */
                                    /* (technically an array of characters) */
    REM BASIC
    count% = 10                     ' count is type integer
    msg$ = "Enter name: "           ' msg is a string

In JavaScript you do not need to specify a type, which generally results in flexibility and simplicity. When a value is used JavaScript attempts to convert it, if necessary, to the proper type based on context. The problem is when the context is not clear, such as asking a user to input 2 numbers and then adding them or comparing them. Are they "string" types or "numerical" types? Because they are input from the keyboard JavaScript considers them to be strings until you perform an operation on them that clearly indicates they are numbers.

In JavaScript it is legal to combine ("concatenate" is the technical term) 2 strings using the "+" operator, and to compare 2 strings for their alphabetical ordering sequence using the Boolean comparison operators such as "<" and ">".

Example 1:

    <!-- strcat.htm -->
    <script type="text/javascript">
        firstName = prompt( "Enter your first name: ", "" );
        lastName = prompt( "Enter your last name: ", "" );
        fullName = firstName + " " + lastName;

        document.write( "firstName = " + firstName + "<br />" );
        document.write( "lastName = " + lastName + "<br />" );
        document.write( "fullName = " + fullName + "<br />" );
    </script>

Try the code


Example 2:

    <!-- strcmp.htm -->
    <script type="text/javascript">
        str1 = prompt( "Enter 1st string of characters: ", "" );
        str2 = prompt( "Enter 2nd string of characters: ", "" );

        // display 2 strings in alphabetical order
        if ( str1 < str2 ) {
            document.write( str1, " < ", str2, "<br />" );
        }
        else if ( str1 > str2 ) {
            document.write( str1, " > ", str2, "<br />" );
        }
        else {
            document.write( str1, " == ", str2, "<br />" );
        }
    </script>

Try the code

Try entering only numbers, like 512 and 256.
So far, so good.
Now try 512 and 9. Hmmm . . .


Example 3:

    <!-- addnum1.htm -->
    <script type="text/javascript">
        n1 = prompt( "1st number: ", "" );      // n1, n2 interpreted as strings
        n2 = prompt( "2nd number: ", "" );
        sum = n1 + n2;
        product = n1 * n2;                      // n1, n2 interpreted as numbers

        document.write ( "n1 = " + n1 + "<br />" );
        document.write ( "n2 = " + n2 + "<br />" );
        document.write( "sum = " + sum + "<br />" );
        document.write( "product = " + product );
    </script>

Try the code

Inputting 2 numbers like 512 and 256 above and comparing them to see which is greater seems to work, but trying it with 512 and 9 will report that 512 is less than 9 because as a string "512" would sort alphabetically lower on the list (i.e. greater ASCII character order) than "9".
In Example 3 JavaScript is concatenating the strings of digits, it is not adding them as numbers because the " + " operator makes contextual sense for strings


A relatively simple solution, if not terribly elegant, is to perform an arithmetic operation on the variable that will:

  1. Force JavaScript to convert it to a numerical context, and
  2. Not change the value of the variable

We can do this by either subtracting 0 from the variable or multiplying the variable by 1:

    n1 = n1 - 0;                    // force numerical context
    n2 = n2 * 1;                    // multiply by 1 also works

    document.write( n1 + n2 );      // correct sum of numbers

A better solution is to perform an explicit data conversion using tools and constructs provided by the language:

Example 4:

    <!-- addnum2.htm -->
    <script type="text/javascript">
        n1 = prompt( "1st number: ", "" );      // n1, n2 interpreted as strings
        n2 = prompt( "2nd number: ", "" );

        n1 = parseInt( n1 );                    // convert to integer type
        n2 = parseFloat( n2 );                  // convert to floating point type
        sum = n1 + n2;                          // n1, n2 summed as numbers

        document.write ( "n1 = " + n1 + "<br />" );
        document.write ( "n2 = " + n2 + "<br />" );
        document.write( "sum = " + sum + "<br />" );
    </script>

Try the code

Use parseFloat() to convert any string to a numerical type for general arithmetic operations; use parseInt() in situations where you specifically require an integer type. This is the preferred solution since it is "self documenting;" you don't really need the comments. Try entering a real number (i.e. 3.1415) for n1 in the example.


Source code for above examples.

strcat.htm
strcmp.htm
addnum1.htm
addnum2.htm
[ TOP ]