Tuesday 8 April 2014

Weak Typing


Most high-level languages,
including C and Java, are strongly typed. That is, a variable must be
declared before it is used, and its type must be included in its declaration. Once a variable is
declared, its type cannot change. At the other end of the spectrum are untyped languages such
as LISP. LISP supports only two primitive data types: atoms and lists. It does not draw any
distinction between strings, integers, functions, and other data types. As a weakly typed
language, JavaScript falls somewhere in between these two extremes. Every variable and
literal has a type, but data types are not explicitly declared. For example, we might define a
variable favNumber to hold our favorite number and set it to a value of 3. Then we might
reassign the variable to be the string value "San Diego".
var favNumber;
favNumber = 3;
favNumber = "San Diego";

it would cause an error or warning to occur. It should start to become clear that weak typing
provides some simplicity since programmers don‘t have to worry about types, but it does so at
the expense of runtime errors and security issues. We‘ll see many issues

throughout both the chapter and the book. For now, the concept is enough. Let‘s begin to look
at each of the types in turn.


JavaScript’s Primitive Types
JavaScript supports five primitive data types: number, string, Boolean, undefined, and null.
These types are referred to as primitive types because they are the basic building blocks from
which more complex types can be built. Of the five, only number, string, and Boolean are real
data types in the sense of actually storing data. Undefined and null are types that arise under
special circumstances.
Numbers
Unlike languages such as C and Java, the number type in JavaScript includes both integer and
floating-point values. All numbers are represented in IEEE 754-1985 double-precision floatingpoint
format. This representation permits exact representation of integers in the range –253 to 253
and floating-point magnitudes as large as ±1.7976 x 10308 and as small as ±2.2250 x 10
Numeric literals in JavaScript can be written in a wide variety of ways, including scientific
notation. When using scientific notation, the exponent is specified with the letter e (which is not
case-sensitive).
Formally (according to the ECMA-262 grammar), decimal literals have one of the following
three forms (parentheses indicate optional components):
DecimalDigits.(DecimalDigits)(Exponent)
.DecimalDigits(Exponent)
DecimalDigits(Exponent)
In plain English, this means that all of the following are valid ways to specify numbers:


10
177.5


-2.71


.333333e77


-1.7E12


3.E-5


128e+100


Note that you should not include leading zeros in your integers. The reason is that JavaScript
also allows numeric literals to be specified in bases other than ten (decimal).
A leading zero indicates to JavaScript that the literal is in a radix other than ten.
Hexadecimal Literals
Programmers often find it convenient to write numbers in hexadecimal (base-16) notation,
particularly when performing bitwise operations. The reason is that it is easier for most

to convert binary to hex than it is to convert binary to decimal. If this doesn‘t make any sense to
you, don‘t fret; if you don‘t already know hex, chances are you won‘t ever have to.
JavaScript‘s hex syntax should be familiar to readers with previous programming experience: a
leading zero, followed by the letter x (not case-sensitive), followed by one or more hexadecimal
digits. Hexadecimal digits are the numbers zero through nine and letters A through F (not casesensitive),
which represent the values zero through fifteen. The following are examples of legal
hexadecimal values:
0x0
0XF8f00
0x1a3C5e7

You cannot use an exponent when using hexadecimal notation (nor with octal notation).
Note While hex may seem to be of limited use in JavaScript used on the Web, consider that
color values in HTML are often set in hex, so it may be more important than you think.
Octal Literals
Although not officially a part of the ECMA-262 specification, almost all JavaScript
implementations allow octal (base-8) numeric literals. Octal literals begin with a leading zero,
and octal digits are the numbers zero through seven. The following are all valid octal literals:
00
0777
024513600
Note The Opera browser’s JavaScript implementations, even up to version 5, do not support
octal. Future versions should support this data type, but programmers should be aware of
this difference when using octal values.



Special Values
Numeric data can take on several special values. When a numeric expression or variable
exceeds the maximum representable positive value, it takes on the special value Infinity.
Likewise, when an expression or variable becomes less than the lowest representable negative
value, it takes on the value –Infinity. These values are sticky in the sense that when one is
used in an expression with other normal values or itself, it causes the entire expression to
evaluate to its value. For example, Infinity minus 100 is still Infinity; it does not become a
representable number. All Infinity values compare equal to each other. Similarly, all –Infinity
values compare equal.
Although an easier way to get an Infinity value is to divide one by zero, the following code
demonstrates what happens when you increment the maximum representable positive value.
var x = 1.7976931348623157e308; // set x to max value
x = x + 1e292; // increment x
alert(x); // show resulting value to user
This code assigns the maximum positive representation to x, increments its least significant
digit, and then shows the user the resulting value x. The result








The other important special value is NaN, which means ―not a number.‖ Numeric data takes on
this value when it is the result of an undefined operation. Common examples of operations that
result in NaN are dividing zero by zero, taking the sine of Infinity, and attempting to add
Infinity to –Infinity. The NaN value is also sticky, but unlike the infinite values it never
compares equal to anything. Because of this, you must use the isNaN() method or compare the
value to itself to determine if a value is NaN. The isNaN() method returns a Boolean indicating
whether the value is NaN. This method is so important that it is a property of the Global object,
so it can be called directly in your scripts. Comparing the value to itself will indicate whether the
value is NaN because it is the only value that does not compare equal to itself!


The following example illustrates the use of both techniques:
var x = 0 / 0; // assign NaN to x
if (x != x) // check via self-equality
{

// do something
}
if (isNaN(x)) // check via explicit call
{
// do something
}
Table 3-1 summarizes these special types
Table 3-1: Summary of Special Numeric Data Values


Special Value                    Result of                                                Comparisons                    Sticky?

 Infinity, –Infinity                Number too large or,                                All Infinity values                   Yes                                        small to be represented                           compare equal to others
                
      NaN                           Undefined operation                                   NaN never
                                                                                                          compares equal to                Yes










                                                                                                         anything, even itself
                                



JavaScript 1.1+ and JScript 2.0+ provide easy access to these special numerical values as
properties of the Number object. These properties are shown in Table 3-2, and the following
example illustrates how they might be used:

Table 3-2: Properties of the Number Object Relevant to Special Numeric Values


Property                                                                                Value

Number.MAX_VALUE                                                   Largest magnitude representable
Number.MIN_VALUE                                                    Smallest magnitude representable      
Number.POSITIVE_INFINITY                                    The special value Infinity 
Number.NEGATIVE_INFINITY                                   The special value –Infinity
Number.NaN                                                                 The special value NaN




// Illustrate that all Infinity values are equal:

var posInf = Number.POSITIVE_INFINITY;


var negInf = Number.NEGATIVE_INFINITY;


alert(posInf == negInf);


// Show the largest magnitude representable:


alert(Number.MAX_VALUE);
A complete discussion of functions and constants supported by JavaScript‘s Math object can
be found in Chapter 7.
Note Division by zero in JavaScript is somewhat consistent with the calculus. Division of a
positive number by zero results in ―infinity,‖ division of a negative number by zero results
in ―negative infinity,‖ and division of zero by zero is ―undefined‖ (NaN).
Data Representation Issues
The fact that numbers in JavaScript are represented as 64-bit floating-point numbers has some
complicated implications and subtle pitfalls. If you‘re working with integers, keep in mind that
only integers in the range –253 to 253 can be represented exactly. As soon as your value (or an
intermediate value in an expression) falls outside of this range, its numeric value becomes an
inexact approximation. This can lead to some surprising behavior:
var x = 9007199254740992; // 2^53
if (x == x + 1)
alert("True! Large integers are only approximations!");

Things get really messy if you work with floating-point numbers. Many such values cannot be
represented exactly, so you might notice (or worse, not notice) ―wrong‖ answers for even simple
computations. For example, consider the following code snippet:
var x = .3333;
x = x * 5;
alert(x);
One would expect x to contain the value 1.6665. However, the actual result is shown here :












Not only is this not the expected result, but this value will not even compare equal to 1.6665!
A basic rule of thumb is to never directly compare fractional values for equality, and to use
rounding to convert numbers into a predetermined number of significant figures. The loss of
precision inherent in floating-point arithmetic can be a very serious issue for applications that
need to calculate precise values. As a result, it‘s probably not a good idea to rely on floatingpoint
arithmetic for important computations unless you have a firm understanding of the issues
involved. The topic is far outside the scope of this book, but interested readers can find tutorials
on floating-point arithmetic online, and more in-depth discussion in books on numerical analysis ,
or mathematical programming..

        " News powered By " 


 
Share:

No comments:

Post a Comment

© World Of Programmers All rights reserved | Theme Designed by Seo Blogger Templates